import { Modal, Form, message } from 'antd';
import ProForm, { ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { save, update } from '@/services/system/role';

const SystemRoleForm = (props) => {
  const [form] = Form.useForm();
  const { formVisible, onSubmit, onCancel, values } = props;

  const saveHandle = async (formValue) => {
    const data = await save(formValue);

    if (data.success) message.success('新建角色成功!');
    else message.error('新建角色失败!');
  };

  const updateHandle = async (formValue) => {
    const data = await update(formValue);

    if (data.success) message.success('修改角色成功!');
    else message.error('修改角色失败!');
  };

  const okHandle = async () => {
    const fieldsValue = await form.validateFields();
    const formValue = { ...values, ...fieldsValue };

    if (formValue.id) await updateHandle(formValue);
    else await saveHandle(formValue);

    onSubmit();
  }

  return (
    <Modal
      destroyOnClose
      title={values.id ? '修改角色信息' : '新增角色信息'}
      visible={formVisible}
      onOk={okHandle}
      onCancel={onCancel}
    >
      <ProForm 
        initialValues={{
          name: values.name,
          remark: values.remark
        }} 
        form={form} submitter={false}
        layout={'horizontal'} labelCol= { {span: 4} } wrapperCol= { {span: 20} }
      >
        <ProFormText  name="name" label="角色名称" rules={[{ required: true, message: '请输入角色名称!' }, {max: 20, message: '角色名称过长!'}]}/>
        <ProFormTextArea  label="备注说明" name="remark" rules={[ {max: 100, message: '备注过长!'}]}/>
      </ProForm>
    </Modal>
  );
};

export default SystemRoleForm;